package com.example.myapplication;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.example.inter.LoginCallBack;
import com.example.util.LoginStudent;
import com.lidroid.xutils.cache.LruDiskCache;

import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity implements LoginCallBack {

    private EditText mPasswordView;
    private EditText mStudentNumber;
    private LoginStudent loginStudent;
    private ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mStudentNumber = (EditText) findViewById(R.id.email);
        mPasswordView = (EditText) findViewById(R.id.password);
        progressBar = (ProgressBar) findViewById(R.id.login_progress);
        Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        Button mSiginButton = (Button) findViewById(R.id.email_resigter_in_button);
        mEmailSignInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });
        mSiginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent= new Intent();
                intent.setClass(MainActivity.this,SiginActivity.class);
                startActivity(intent);
            }
        });
        getSh();


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    private boolean isEmailVaild(String studentnumber) {
        return studentnumber.length()>4;
    }

    private boolean isPasswordValid(String password) {
        return password.length() > 4;
    }

    private void attemptLogin() {
        mStudentNumber.setError(null);
        mPasswordView.setError(null);
        View focusView = null;
        boolean cancle = false;
        String email = mStudentNumber.getText().toString();
        String password = mPasswordView.getText().toString();
        if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
            mStudentNumber.setError(getString(R.string.error_field_required));
            focusView = mStudentNumber;
            cancle = true;
        }
        if (TextUtils.isEmpty(email)) {
            mStudentNumber.setError(getString(R.string.error_field_required));
            focusView = mStudentNumber;
            cancle = true;
        } else if (!isEmailVaild(email)) {
            mStudentNumber.setError(getString(R.string.error_invalid_password));
        }
        if (TextUtils.isEmpty(password)) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancle = true;
        }
        if (cancle) {
            focusView.requestFocus();
        }else{
            loginStudent = new LoginStudent();
            loginStudent.getLoginInfo(email,password,this);
            progressBar.setVisibility(View.VISIBLE);
        }
    }

    private void attemptLogin2(String email,String password) {
        loginStudent = new LoginStudent();
        loginStudent.getLoginInfo(email,password,this);
        progressBar.setVisibility(View.VISIBLE);
    }

    public void getSh(){

        SharedPreferences sh = getSharedPreferences("student_info",MODE_PRIVATE);
        String username = sh.getString("username",null);
        String userpassword = sh.getString("password",null);

        if(username!=null&&userpassword!=null){

            attemptLogin2(username,userpassword);
            SharedPreferences.Editor editor = sh.edit();
            editor.putString("username", username);
            editor.putString("password", userpassword);
            editor.commit();

        }

    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onSuccess(String info) {
        progressBar.setVisibility(View.GONE);
        try {
            JSONObject jsonObject = new JSONObject(info);
            Log.i("--->>>login",jsonObject.toString());
            String errcode = jsonObject.getString("errcode");
            if(errcode.equals("0")){
                SharedPreferences sharedPreferences =
                        getSharedPreferences("student_info",MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("username", mStudentNumber.getText().toString());
                editor.putString("password", mPasswordView.getText().toString());
                editor.commit();
                Intent intent = new Intent();
                intent.setClass(MainActivity.this,WorkinfoActivity.class);
                startActivity(intent);
                Toast.makeText(getApplicationContext(),"yes",Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(getApplicationContext(),"no",Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

    @Override
    public void onFailed() {
        progressBar.setVisibility(View.GONE);
        Toast.makeText(MainActivity.this,"shibai",Toast.LENGTH_SHORT).show();
    }
}
